package MULE.Model.Logic;

import java.awt.event.ActionEvent;

import javax.swing.ButtonModel;

import MULE.Model.*;
import MULE.Model.Panel.*;

/**
 * Logic module for game configuration. Allows user to configure game, map, and
 * number of players.
 * 
 */
public class GameConfigLogic extends MulePresenter {

	/**
	 * An enumeration of this presenter's supported action commands.
	 */
	public enum ActionCommand {
		NEXT
	}

	/**
	 * Creates a new GameConfigLogic module which listens to the given view.
	 * 
	 * @param view
	 *            The view this module should listen to.
	 */
	public GameConfigLogic(GameConfigPanel view) {
		super(view);
		// Listen to game config panel's next button.
		view.addNextButtonListener(this);
	}

	/**
	 * Returns a new game object with given difficulty setting.
	 * 
	 * @param diff
	 *            The game difficulty as a string.
	 * @return A new game object with given difficulty.
	 */
	public void createGameWithAttributes(int numPlayers, String diffStr,
			String mapStr) {
		// Process inputs.
		Game.Difficulty diff = Game.getDifficulty(diffStr);
		Map.MapType mapType = Map.getMapType(mapStr);
		// Create new game with inputs.
		Game game = new Game(numPlayers, diff, new Map(mapType));
		// Initialize main game logic and panels.
		MuleDriver.initCoreLogic(game);
	}

	/**
	 * Tells the application to show the player configuration panel.
	 */
	public void showPlayerConfigPanel() {
		PlayerConfigPanel pConfigPanel = new PlayerConfigPanel(
				Race.getRaceNames(), PlayerColor.getColorNames());
		PlayerConfigLogic pConfigLogic = new PlayerConfigLogic(pConfigPanel);
		pConfigLogic.showView();
	}

	/**
	 * Event handler. Called when the game configuration panel receives input.
	 * 
	 * @param e
	 *            The event which was fired on the panel.
	 */
	public void actionPerformed(ActionEvent e) {
		// Next button was pressed.
		if (e.getActionCommand().equals(ActionCommand.NEXT.toString())) {
			GameConfigPanel gcp = (GameConfigPanel) view;
			ButtonModel diffSelect = gcp.getDifficultySelection();
			ButtonModel mapTypeSelect = gcp.getMapTypeSelection();
			ButtonModel playerNumSelect = gcp.getPlayerNumSelection();
			// Make sure all fields have a selection.
			if (diffSelect != null && mapTypeSelect != null
					&& playerNumSelect != null) {
				// Get game attributes.
				String diffStr = diffSelect.getActionCommand();
				String mapTypeStr = mapTypeSelect.getActionCommand();
				int numPlayers = gcp.getNumPlayers();
				// Create a new game with selected attributes.
				createGameWithAttributes(numPlayers, diffStr, mapTypeStr);
				showPlayerConfigPanel();
			}
		}
	}
}
